import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:win32audio/win32audio.dart';

import './data_sharing.service.dart';

/// Extracts local file associated icon and displays it as an image.
class FileAssociatedIcon extends StatefulWidget {
  const FileAssociatedIcon(this.fileFullName, {super.key});

  final String fileFullName;

  @override
  State<FileAssociatedIcon> createState() => _FileAssociatedIconState();
}

class _FileAssociatedIconState extends State<FileAssociatedIcon> {
  final String _fileBytesCollectionKey = 'fileBytesCollection';
  final double size = 32.0;

  Uint8List? _fileBytes;

  @override
  void initState() {
    super.initState();

    extractFileIcon();
  }

  @override
  Widget build(BuildContext context) {
    return _fileBytes == null
        ? FaIcon(
            FontAwesomeIcons.file,
            size: size,
          )
        : Image.memory(
            _fileBytes!,
            width: size,
            height: size,
          );
  }

  /// Extracts file associated icon data.
  Future<void> extractFileIcon() async {
    if (DataSharing.get<Map<String, Uint8List>>('fileBytesCollection') ==
        null) {
      DataSharing.set<Map<String, Uint8List>>(_fileBytesCollectionKey, {});
    }

    var result = DataSharing.get<Map<String, Uint8List>>(
        'fileBytesCollection')![widget.fileFullName];

    if (result == null) {
      result = await WinIcons().extractFileIcon(widget.fileFullName);
      // result = PlatformService.getEncodedImageBytes(widget.fileFullName);

      DataSharing.get<Map<String, Uint8List>>(
          'fileBytesCollection')![widget.fileFullName] = result!;
    }

    if (mounted) {
      setState(() => _fileBytes = result);
    }
  }
}
